//
//  OptionViewController.m
//  iMiniTao
//
//  Created by liunian on 13-8-16.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "OptionViewController.h"
#import "DAAppsViewController.h"
#import "FqViewController.h"
#import "ALAlertBanner.h"
#import "AppDelegate.h"
#import "DesktopController.h"
#import "FeedbackViewController.h"

#define kDefaultBottomBarHeight           38

@interface OptionViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property (nonatomic, retain) UILabel       *theTitle;
@property (nonatomic, retain) UIImageView          *navImageView;
@property (nonatomic, retain) UIImageView          *bottomImageView;

@property (nonatomic, retain) UITableView   *tableView;
@property (nonatomic, retain) UIView        *headView;

@property (nonatomic, retain) NSString  *sinaName;
@property (nonatomic, retain) NSString  *txName;
@end

@implementation OptionViewController
- (void)dealloc{
    BMLog(@"dealloc");
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];    
    [self.view addSubview:self.navImageView];
    [self.view addSubview:self.bottomImageView];
    [self.theTitle setText:@"设置"];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [MobClick beginLogPageView:@"选项视图"];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"选项视图"];
}
- (void)back{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(long)fileSizeForDir:(NSString*)path//计算文件夹下文件的总大小
{
    long size = 0;
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    for(int i = 0; i<[array count]; i++)
    {
        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
        
        BOOL isDir;
        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
        {
            NSDictionary *fileAttributeDic = [fileManager attributesOfItemAtPath:fullPath error:nil];
            size += fileAttributeDic.fileSize;
        }
        else
        {
            [self fileSizeForDir:fullPath];
        }
    }
    return size;
    
}
//单位:MB
- (NSString *)sizeCache{
    NSArray*paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
    NSString*cachesDir = [paths objectAtIndex:0];
    NSString *ImageCachePath = [cachesDir stringByAppendingPathComponent:@"ImageCache"];
    long ImageCacheSize = [self fileSizeForDir:ImageCachePath];
    
    NSString *urlCachePath = [cachesDir stringByAppendingPathComponent:@"URLCACHE"];
    long urlCacheSize = [self fileSizeForDir:urlCachePath];
    
    long totalSize = ImageCacheSize + urlCacheSize;
    const unsigned int bytes = 1024*1024 ;   //字节数，如果想获取KB就1024，MB就1024*1024
    NSString *string = [NSString stringWithFormat:@"%.2f",(1.0 *totalSize/bytes)];
    BMLog(@"ImageCacheSize:%ld,urlCacheSize:%ld",ImageCacheSize,urlCacheSize);
    return string;
}
- (BOOL)cleanAllCache{
    [[SDImageCache sharedImageCache] clearDisk];
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *urlCache_doc = [cachePath stringByAppendingPathComponent:@"URLCACHE"];
    
    BOOL result = [[NSFileManager defaultManager] removeItemAtPath:urlCache_doc error:nil];
    
    if (result ){
        return YES;
    }
    return NO;
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        return;
    }
    switch (alertView.tag) {
        case 10011:
        {
        }
            break;
        case 10012:
        {
        }
            break;
        case 10013:
        {
        ALAlertBannerStyle randomStyle = ALAlertBannerStyleSuccess;
        NSString *aTitle = @"成功";
        NSString *aContent = @"缓存清理成功!";
        if (![self cleanAllCache]) {
            aTitle = @"失败";
            aContent = @"清理缓存失败,请重试!";
            randomStyle = ALAlertBannerStyleFailure;
        }
        
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        ALAlertBannerPosition position = ALAlertBannerPositionUnderNavBar;
        ALAlertBanner *banner = [ALAlertBanner alertBannerForView:appDelegate.window style:randomStyle position:position title:aTitle subtitle:aContent tappedBlock:^(ALAlertBanner *alertBanner) {
            [alertBanner hide];
        }];
        banner.secondsToShow = 2;
        banner.showAnimationDuration = 0.25;
        banner.hideAnimationDuration = 0.20;
        [banner show];

            [self.tableView reloadData];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
        {
            return 3;
        }
            break;
        case 1:
        {
            return 3;
        }
            break;
        default:
            break;
    }
    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    switch (section) {
        case 0:
        {
            return @"程序";
        }
            break;
        case 1:
        {
            return @"其他";
        }
            break;
        default:
            break;
    }
    return @"其他";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    switch (indexPath.section) {

        case 0:
        {
            switch (indexPath.row) {
                case 0:
                {
                    cell.textLabel.text = @"清理缓存文件";
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@MB",[self sizeCache]];
                }
                    break;
                case 1:
                {
                    cell.textLabel.text = @"帮助说明";
                    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
                }
                    break;
                case 2:
                {
                cell.textLabel.text = @"设置桌面背景";
                [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    cell.textLabel.text = @"给我们打分";
                }
                    break;
                case 1:
                {
                    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
                    cell.textLabel.text = @"版本更新";
                }
                    break;
                case 2:
                {
                    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
                    cell.textLabel.text = @"反馈和建议";
                }
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
    return cell;
}


#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定清理缓存文件么?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alert setTag:10013];
                    [alert show];
                    
                }
                    break;
                case 1:
                {
                    FqViewController *fqVC = [[FqViewController alloc] init];
                    [self.navigationController pushViewController:fqVC animated:YES];
                }
                    break;
                case 2:
                {
                    DesktopController *desktopVC = [[DesktopController alloc] init];
                    [self.navigationController presentViewController:desktopVC animated:YES completion:^{
                    
                    }];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    NSString *appUrlString = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%u?mt=8",kAPPID];
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appUrlString]];
                
                }
                    break;
                case 1:
                {
                    [MobClick checkUpdateWithDelegate:self selector:@selector(callBackSelectorWithDictionary:)];
                   
                }
                    break;
                case 2:
                {
                    
                    FeedbackViewController *feedback = [[FeedbackViewController alloc] init];
                    [self.navigationController pushViewController:feedback animated:YES];

                }
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
    
}

- (void)callBackSelectorWithDictionary:(NSDictionary *)appUpdateInfo{
    BMLog(@"%@",appUpdateInfo);
    BOOL update = [[appUpdateInfo objectForKey:@"update"] boolValue];
    if (update) {
        [MobClick checkUpdate:@"有新版本更新啦！" cancelButtonTitle:@"我爱怀旧" otherButtonTitles:@"我爱潮流"];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            ALAlertBannerStyle randomStyle = ALAlertBannerStyleSuccess;
            ALAlertBannerPosition position = ALAlertBannerPositionBottom;
            ALAlertBanner *banner = [ALAlertBanner alertBannerForView:appDelegate.window style:randomStyle position:position title:@"提示" subtitle:@"您使用的已经是最新的版本!" tappedBlock:^(ALAlertBanner *alertBanner) {
                NSLog(@"tapped!");
                [alertBanner hide];
            }];
            banner.secondsToShow = 2;
            banner.showAnimationDuration = 0.25;
            banner.hideAnimationDuration = 0.20;
            [banner show];
            return;
            
        });
    }
    
}

#pragma mark - getter
- (UIImageView *)navImageView{
    if (!_navImageView) {
        _navImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, kDefaultBottomBarHeight)];
        _navImageView.userInteractionEnabled = YES;
        _navImageView.backgroundColor = COLOR_RGB_NAV;
    }
    return _navImageView;
}

- (UILabel *)theTitle{
    if (!_theTitle) {
        _theTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 4, 300, 40)];
        _theTitle.backgroundColor = [UIColor clearColor];
        _theTitle.textAlignment = [Util getAlign:ALIGNTYPE_LEFT];
        _theTitle.font = FONT_TITLE(18.0f);
        _theTitle.textColor = [UIColor flatWhiteColor];
        [self.navImageView addSubview:_theTitle];
    }
    return _theTitle;
}
- (UIImageView *)bottomImageView{
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - kDefaultBottomBarHeight - _kSpaceHeight, 320, kDefaultBottomBarHeight)];
        _bottomImageView.backgroundColor = COLOR_RGB_BOTTOM;
        _bottomImageView.userInteractionEnabled = YES;
        [_bottomImageView setImage:IMGNAMED(@"bottomTabBarBackground.png")];
        
        UIImage *imgBack = IMGNAMED(@"btn_back.png");
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, floorf((_bottomImageView.bounds.size.height-imgBack.size.height)/2), imgBack.size.width, imgBack.size.height);
        [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:back];
        
        [back setBackgroundImage:IMGNAMED(@"btn_dis.png") forState:UIControlStateNormal];
        [back setBackgroundImage:IMGNAMED(@"btn_dis_light.png") forState:UIControlStateHighlighted];
    }
    return _bottomImageView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,
                                                                   self.navImageView.frame.origin.y+self.navImageView.bounds.size.height,
                                                                   320,
                                                                   self.view.bounds.size.height - kDefaultBottomBarHeight-self.navImageView.frame.origin.y-self.navImageView.bounds.size.height - _kSpaceHeight)
                      style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView setBackgroundView:nil];
        [_tableView setBackgroundColor:COLOR_BG_VIEW];
        [_tableView setTableHeaderView:self.headView];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 150)];
        
        UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake((CGRectGetWidth(_headView.frame) - 72)/2, 20, 72, 72)];
        logo.userInteractionEnabled = YES;
        logo.backgroundColor = [UIColor clearColor];
        [logo setImage:IMGNAMED(@"Icon-72.png")];
        [_headView addSubview:logo];
        
        logo.layer.shadowColor = [UIColor grayColor].CGColor;
        logo.layer.shadowOffset = CGSizeMake(0, -1);
        logo.layer.shadowOpacity = 0.5;
        logo.layer.shadowRadius = 5.0;
        
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 280, 30)];
        [name setBackgroundColor:[UIColor clearColor]];
        [name setLineBreakMode:NSLineBreakByCharWrapping];
        [name setNumberOfLines:0];
        [name setText:[NSString stringWithFormat:@"正品街-京东精选"]];
        [name setFont:[UIFont systemFontOfSize:18]];
        [name setTextAlignment:[Util getAlign:ALIGNTYPE_CENTER]];
        [name setTextColor:[UIColor flatDarkBlackColor]];
        [_headView addSubview:name];
        
        UILabel *version = [[UILabel alloc] initWithFrame:CGRectMake(20, 130, 280, 20)];
        [version setBackgroundColor:[UIColor clearColor]];
        [version setLineBreakMode:NSLineBreakByCharWrapping];
        [version setNumberOfLines:0];
        [version setText:[NSString stringWithFormat:@"Ver %@",APP_VERSION]];
        [version setFont:[UIFont systemFontOfSize:14]];
        [version setTextAlignment:[Util getAlign:ALIGNTYPE_CENTER]];
        [version setTextColor:[UIColor flatBlackColor]];
        [_headView addSubview:version];
    }
    return _headView;
}
@end
